<?php

namespace Lims\CreditBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Utils\SecurityBundle\CustomClass\SecurityFunctions;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Lims\CreditBundle\Exception\CreditException;

class CreditController extends Controller
{
    private $msg = null;
    
    public function listAction()
    {
        $em = $this->get('doctrine')->getManager();
        $creditList = $em->getRepository('LimsMainBundle:Credit')->findForList();        
        return $this->render('LimsCreditBundle:Credit:list.html.twig', array(
            'creditList' => $creditList
        ));
    }
    
    public function newAction($registerNumber = null)
    {
        $em = $this->get('doctrine')->getManager();
        $creditType = $em->getRepository('LimsMainBundle:CreditType')->findForList();                
        $creditDedication = $em->getRepository('LimsMainBundle:CreditDedication')->findForList();
        $creditPaymentType = $em->getRepository('LimsMainBundle:CreditPaymentType')->findForList();              
        $currencyList = $em->getRepository('LimsMainBundle:Currency')->findForList();
        
        $creditQualityList = $em->getRepository('LimsMainBundle:Quality')->findForList();
        $contractList = $em->getRepository('LimsMainBundle:Contract')->findAvailableContracts();
        
        return $this->render('LimsCreditBundle:Credit:new.html.twig', array(
            'creditType' => $creditType,
            'creditDedication' => $creditDedication,
            'creditPaymentType' => $creditPaymentType,
            'currencyList' => $currencyList,
            'registerNumber' =>$registerNumber,
            'creditQualityList' => $creditQualityList,
            'contractList' => $contractList
        ));
    }
    
    public function createAction()
    {
        $em = $this->get('doctrine')->getManager();
        
        $creditData = $this->checkCreditNew();
        $contractId = $this->checkContractData();
        $scheduleData = $this->checkScheduleNew();
        $partnerData = $this->checkPartnerNew();
        $userId = $this->container->get('security.context')->getToken()->getUser()->getId();
        
        if($this->msg != null)
        {
            $this->get('session')->getFlashBag()->add('error', $this->msg);
            return new RedirectResponse($this->getRequest()->headers->get('referer'));
        }
        
        try{
            // SAVE CREDIT                
            $credit = $em->getRepository('LimsMainBundle:Credit')->saveCredit($em, $creditData, $userId);
            
            // SAVE CONTRACT
            $creditContractMap = $em->getRepository('LimsMainBundle:CreditContractMap')->saveContract($em, $credit, $contractId, $userId);
            
            // SAVE QUALITY
            $creditQualityMap = $em->getRepository('LimsMainBundle:CreditQualityMap')->saveCreditQuality($em, $credit, $creditData['credit_quality_map'], $userId);
            
            // SAVE SCHEDULE
            $schedule = array();            
            foreach ($scheduleData['schedule_date'] as $index => $v){                
                $creditSchedule = $em->getRepository('LimsMainBundle:CreditSchedule')->saveSchedule($em, $index, $scheduleData, $credit, $userId);                
                array_push($schedule, $creditSchedule);
            }
            
            if($partnerData != null)
            {
                foreach($partnerData AS $partner){
                    $partnerObject = $em->getRepository('LimsMainBundle:Partner')->savePartner($em, $credit->getDebtor(), $partner, $credit, $userId);
                }
            }
            
            if($this->msg != null)
            {
                $this->get('session')->getFlashBag()->add('error', $this->msg);
                return new RedirectResponse($this->getRequest()->headers->get('referer'));
            }
            
            // COMMIT TO DB
            $em->flush();
            
            $this->get('session')->getFlashBag()->add('notice', $creditData['credit_register_number'].' регистертэй хэрэглэгчид зээл амжилттай нэмлээ');
            return new RedirectResponse($this->generateUrl('lims_credit_list'));
            
        }  catch (CreditException $e){
            $this->get('session')->getFlashBag()->add('error', $e->message);
            return new RedirectResponse($this->getRequest()->headers->get('referer'));
        } catch(\Exception $e)
        {
            var_dump($e);die;
            $this->get('session')->getFlashBag()->add('error', 'Амжилтгүй боллоо');
            return new RedirectResponse($this->getRequest()->headers->get('referer'));   
        }
    }
    
    private function checkCreditNew()
    {       
        $creditData = array();
        
        /**
         * CREDIT DOCUMENT NUMBER шалгуур
         */
        if(!isset($_POST['credit_register_number']))
        {
            $this->msg .= $this->container->getParameter('ERROR_MSG_CREDIT_1');
        }else if(strlen($_POST['credit_register_number']) == 0)
        {
            $this->msg .= $this->container->getParameter('ERROR_MSG_CREDIT_1');   
        }else{
            $creditData['credit_register_number'] = SecurityFunctions::clear($_POST['credit_register_number']);
        }
        
        $creditData = $_POST;
        $creditData['created_user_id'] = $this->container->get('security.context')->getToken()->getUser()->getId();
        $creditData['customer_id'] = $this->container->get('security.context')->getToken()->getUser()->getCustomer()->getId();
        return $creditData;
    }
    
    private function checkScheduleNew()
    {
        $scheduleData = array();
        
        // daraa ni shalgaltaa hiinee.
        
        $scheduleData = $_POST;
        return $scheduleData;
    }
    
    private function checkContractData()
    {
        $contractData = array();
        $contractData = $_POST['credit_contract_number'];
        
        // daraa ni shalgaltaa hiinee.
        
        return $contractData;
    }
    
    
    private function checkPartnerNew()
    {
        $partnerDataList = array();                
        if(isset($_POST['partner_popup_register_number']))
        {
            if(count($_POST['partner_popup_register_number']) > 0){
                for($i = 0; $i < count($_POST['partner_popup_register_number']); $i++){
                    
                    $partnerData['partnerType'] = isset($_POST['partner_type'][$i]) ? $_POST['partner_type'][$i] : null;
                    $partnerData['partnerRegisterNumber'] = isset($_POST['partner_popup_register_number'][$i]) ? $_POST['partner_popup_register_number'][$i] : null;
                    $partnerData['partnerFamilyName'] = isset($_POST['partner_popup_family_name'][$i]) ? $_POST['partner_popup_family_name'][$i] : null;
                    $partnerData['partnerLastName'] = isset($_POST['partner_popup_last_name'][$i]) ? $_POST['partner_popup_last_name'][$i] : null;
                    $partnerData['partnerFirstName'] = isset($_POST['partner_popup_first_name'][$i]) ? $_POST['partner_popup_first_name'][$i] : null;
                    $partnerData['partnerAddress1Name'] = isset($_POST['partner_popup_address_1'][$i]) ? $_POST['partner_popup_address_1'][$i] : null;
                    $partnerData['partnerAddress2Name'] = isset($_POST['partner_popup_address_2'][$i]) ? $_POST['partner_popup_address_2'][$i] : null;
                    $partnerData['partnerAddressFullName'] = isset($_POST['partner_popup_address_full'][$i]) ? $_POST['partner_popup_address_full'][$i] : null;
                    $partnerData['partnerEmail'] = isset($_POST['partner_popup_email'][$i]) ? $_POST['partner_popup_email'][$i] : null;
                    $partnerData['partnerPhone'] = isset($_POST['partner_popup_phone'][$i]) ? $_POST['partner_popup_phone'][$i] : null;
                    
                    $partnerDataList[$i] = $partnerData;
                }
            }
        }
        
        return $partnerDataList;
    }
}
